package com.tarena.lbs.basic.web.repoistory.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.config.ESClientConfig;
import com.tarena.lbs.basic.web.mapper.StoreMapper;
import com.tarena.lbs.basic.web.repoistory.StoreRepository;
import com.tarena.lbs.pojo.basic.bo.StoreBO;
import com.tarena.lbs.pojo.basic.dos.StoreDO;
import com.tarena.lbs.pojo.basic.param.StoreParam;
import com.tarena.lbs.pojo.basic.query.AreaStoreQuery;
import com.tarena.lbs.pojo.basic.query.StoreQuery;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Repository
public class StoreRepositoryImpl implements StoreRepository {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private RestHighLevelClient client;

    @Override
    public BasePageList<StoreBO> storeList(StoreQuery query) {
        log.info("店铺分页数据,pageNo:{},pageSize:{}",query.getPageNo(),query.getPageSize());
        //1.开启分页
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        //2.sql select
        List<StoreDO> dos= storeMapper.selectStoresByPage(query);
        //3.封装转化返回
        if (CollectionUtils.isNotEmpty(dos)){
            PageInfo<StoreDO> pageDos=new PageInfo<>(dos);
            List<StoreBO> bos=pageDos.getList().stream().map(storeDO->{
                StoreBO bo=new StoreBO();
                BeanUtils.copyProperties(storeDO,bo);
                return bo;
            }).collect(Collectors.toList());
            return new BasePageList<>(bos,pageDos.getTotal());
        }
        return new BasePageList<>(null,0L);
    }

    @Override
    public Integer saveStore(StoreParam storeParam) {
        //1.db es存 都转成DO 来存储 保证数据 可用的 缺少 填补
        StoreDO storeDO=new StoreDO();
        //1.1 字段相同 拷贝
        BeanUtils.copyProperties(storeParam,storeDO);
        //1.2 时间填补(应该业务使用BO bo传给仓库成转化do)
        storeDO.setCreateTime(new Date());
        storeDO.setUpdateTime(storeDO.getCreateTime());
        storeDO.setStoreLatitude(storeParam.getLatitude());
        storeDO.setStoreLongitude(storeParam.getLongitude());
        storeDO.setStoreImagesId(storeParam.getStoreImagesIds().get(0));
        //1.3 拼接latitude和longitude成为 location
        GeoPoint geoPoint= new GeoPoint(Double.valueOf(storeParam.getLatitude()),
                                Double.valueOf(storeParam.getLongitude()));
        storeDO.setLocation(geoPoint);
        //2. 写入数据库 获取id
        log.debug("P2-新增门店,数据库层:{}",storeDO);
        storeMapper.insertDb(storeDO);
        //3. 写入 es
        insertES(storeDO);
        return storeDO.getId();
    }

    @Override
    public BasePageList<StoreBO> getStoresByAreasAndBusiness(Integer id, AreaStoreQuery query) {
        PageHelper.startPage(query.getPageNo(),query.getPageSize());
        List<StoreDO> dos=storeMapper.selectStoreByAreasAndBusiness(id,query);
        if (CollectionUtils.isNotEmpty(dos)){
            PageInfo<StoreDO> pageDos=new PageInfo<>(dos);
            List<StoreBO> bos=pageDos.getList().stream().map(storeDO->{
                StoreBO bo=new StoreBO();
                BeanUtils.copyProperties(storeDO,bo);
                return bo;
            }).collect(Collectors.toList());
            return new BasePageList<>(bos,pageDos.getTotal());
        }
        return new BasePageList<>(null,0L);
    }

    private void insertES(StoreDO storeDO) {
        log.debug("进入es方法数据:{}",storeDO);
        //不需要创建索引 手动创建lbs_store
        IndexRequest indexRequest=new IndexRequest("lbs_store");
        //指定索引,指定id,转化数据成为json 写入文档doc
        indexRequest.id(storeDO.getId()+"");
        //填写 文档具体数据 storeDO转化成json
        String sourceStore= JSON.toJSONString(storeDO);
        indexRequest.source(sourceStore, XContentType.JSON);
        try{
            log.debug("存入es的数据:{}",sourceStore);
            client.index(indexRequest, RequestOptions.DEFAULT);
        }catch (Exception e){
            log.error("新增文档异常",e);
        }
    }
}
